package com.edais.service.imp;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.edais.dao.LoanDao;
import com.edais.dao.UserVouchersDao;
import com.edais.domain.Scattered;
import com.edais.domain.UserVouchers;
import com.edais.domain.VouchersRule;
import com.edais.service.UserVouchersService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;
import com.edais.util.DecimalFormatUtil;
import com.edais.vo.UserVouchersVo;
import com.lb.sssq.dao.DepositDao;
import com.lb.sssq.domain.Scattered_sssq;
@Service

@Transactional
public class UserVouchersServiceImpl implements UserVouchersService {
	private static final Log logger = LogFactory.getLog(UserVouchersServiceImpl.class);
	
	@Autowired
	private UserVouchersDao userVouchersDao;
	
	@Autowired
	private LoanDao loanDao;
	
	@Autowired
	private DepositDao depositDao;
	
	
	/**
	 * 查询我的加息券
	 */
	@Override
	public Map<String, Object> myVouchers(Map<String, Object> paramsMap)
			throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		String userId = paramsMap.get("userId").toString();
		String loanId = paramsMap.get("loanId")==null?"":paramsMap.get("loanId").toString();
		
		if(StringUtils.isNotBlank(loanId)){
			//查询标的信息
			Scattered sc = loanDao.queryScatteredByLoanId(paramsMap);
			
			if(sc!=null){
				//产品ID
				String productType = sc.getPlanId().toString();
				paramsMap.put("productType", productType);
				if(productType.equals("108")){
					if(sc.getRemanDays()!=null && sc.getRemanDays()>0){
						paramsMap.put("remanPeriods", sc.getRemanDays());
					}else{
						paramsMap.put("remanPeriods", sc.getRemanPeriods()*30);
					}
				}
			}
		}
		
		List<UserVouchers> userVoucherList = userVouchersDao.queryVochersByUserId(paramsMap);
		
		int totalNum = userVouchersDao.queryVochersByUserIdCount(paramsMap);
		
		/*List<UserVouchersVo> list = (List<UserVouchersVo>) RedisOperateUtil.lrangeObjectForPage(RedisContant.KEY_VOUCHERS_LIST +  userId,
				Integer.parseInt(paramsMap.get("current").toString()),Integer.parseInt(paramsMap.get("rowEnd").toString()));
		
		if(list !=null && list.size()>0){
			rtnMap.put("listSize", list.size());
			rtnMap.put("totalNum", RedisOperateUtil.getString(RedisContant.KEY_VOUCHERS_LIST_TOTAL_NUM + userId));
			rtnMap.put("list", list);
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg_cn", "查询成功"); 
			return rtnMap;
		}*/
		
		List<UserVouchersVo> list  = new ArrayList<UserVouchersVo>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		for(UserVouchers uv :userVoucherList){
			UserVouchersVo vo = new UserVouchersVo();
			vo.setUserId(Long.parseLong(userId));
			vo.setVoucherAmount(uv.getVoucher_amount().toString());
			String voucherDesc = "投资满"+uv.getInvestment_amount().toString()+"元可用";
			vo.setVoucherDesc(voucherDesc);
			paramsMap.put("voucherId", uv.getVoucher_type_id());
			VouchersRule vouchersRule = this.userVouchersDao.queryVouchersRuleById(paramsMap);
			
			vo.setVouchersRule(vouchersRule);
			String validityPeriodDesc = sdf.format(uv.getEnddate())+"到期";
			vo.setValidityPeriodDesc(validityPeriodDesc);
			vo.setVoucherId(uv.getId().toString());
			vo.setVoucherTypeId(vouchersRule.getProduct_type());
			vo.setInvestmentAmount(uv.getInvestment_amount().toString());
			//拉取适合此代金券的产品
			/*String scatteredLoanDesc = "";*/
			if(vouchersRule.getProduct_type().equals("108")){
				paramsMap.put("voucherProductType", vouchersRule.getProduct_type());
				paramsMap.put("voucherMinlockperiod", vouchersRule.getMinlockperiod());
				List<Scattered> scatteredList = this.loanDao.queryScatteredByVouchersId(paramsMap);
				vo.setScatteredList(scatteredList);
				/*for(Scattered st:scatteredList){
					scatteredLoanDesc += st.getProductName()+"、";
				}*/
			}else if(vouchersRule.getProduct_type().equals("109")){
				paramsMap.put("finaceId", "1");
				paramsMap.put("startSellingTime",CommonUtil.getDateYYYYMMDDHH24MM());
				List<Scattered_sssq> scatteredListSssq = this.depositDao.queryScatteredLoanInfo(paramsMap);
				List<Scattered> scatteredList  = new ArrayList<Scattered>();
				for(Scattered_sssq st:scatteredListSssq){
					/*scatteredLoanDesc += st.getProductName()+"、";*/
					if(st.getFinishedRatio().compareTo(new BigDecimal(100))<0){
						Scattered scattered = st;
						scatteredList.add(scattered);
					}
					
				}
				vo.setScatteredList(scatteredList);
			}
			/*if(StringUtils.isNotBlank(scatteredLoanDesc)){
				scatteredLoanDesc = scatteredLoanDesc.substring(0,scatteredLoanDesc.length()-2);
			}*/
			
			vo.setScatteredLoanDesc(vouchersRule.getProduct_type_desc());
			list.add(vo);
		}
		rtnMap.put("list", list);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		rtnMap.put("listSize", userVoucherList.size());
		rtnMap.put("totalNum", totalNum);
		
		/** 将数据同步到Redis **/
		/*RedisOperateUtil.rpushObjectAll(RedisContant.KEY_VOUCHERS_LIST +  userId, list);
		RedisOperateUtil.setString(RedisContant.KEY_VOUCHERS_LIST_TOTAL_NUM + userId, String.valueOf(totalNum));
		*/
		return rtnMap;
	}
	
	/**
	 * 我的账户 查询所有代金券条数
	 */
	@Override
	public int queryVouchersByUserAllCount(Map<String, Object> paramsMap)
			throws Exception {
		return userVouchersDao.queryVochersByUserIdCount(paramsMap);
	}
	
	@Override
	public Map<String, Object> getScatteredInfoByVoucherId(
			Map<String, Object> paramsMap) throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		UserVouchers  userVouchers = this.userVouchersDao.queryUserVochersById(paramsMap);
		
		if(userVouchers==null){
			rtnMap.put("rescode", Consts.ERROR_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "代金券不存在！");
			return rtnMap;
		}
		
		paramsMap.put("voucherId", userVouchers.getVoucher_type_id());
		VouchersRule vouchersRule = this.userVouchersDao.queryVouchersRuleById(paramsMap);
		List<Scattered> scatteredList = new ArrayList<Scattered>();
		if(vouchersRule.getProduct_type().equals("108")){
			paramsMap.put("voucherProductType", vouchersRule.getProduct_type());
			paramsMap.put("voucherMinlockperiod", vouchersRule.getMinlockperiod());
			scatteredList = this.loanDao.queryScatteredByVouchersId(paramsMap);
		}else if(vouchersRule.getProduct_type().equals("109")){
			paramsMap.put("finaceId", "1");
			List<Scattered_sssq> scatteredListSssq = this.depositDao.queryScatteredLoanInfo(paramsMap);
			for(Scattered_sssq st:scatteredListSssq){
				Scattered scattered = st;
				scatteredList.add(scattered);
			}
		}
		
		rtnMap.put("list", scatteredList);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		rtnMap.put("listSize", scatteredList.size());
		rtnMap.put("totalNum", scatteredList.size());
		return rtnMap;
	}
	
	/**
	 * 根据参数查询代金券
	 */
	@Override
	public List<UserVouchers> queryVouchersByParams(
			Map<String, Object> paramsMap) throws Exception {
		return this.userVouchersDao.queryVouchersByParams(paramsMap);
	}
	
	
	@Override
	public int queryVouchersByParamsCount(Map<String, Object> paramsMap)
			throws Exception {
		return this.userVouchersDao.queryVouchersByParamsCount(paramsMap);
	}
	@Override
	public Map<String, Object> queryUserVochersById(
			Map<String, Object> paramsMap) throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		UserVouchers  userVouchers = this.userVouchersDao.queryUserVochersById(paramsMap);
		
		if(userVouchers==null){
			rtnMap.put("rescode", Consts.ERROR_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "代金券不存在！");
			return rtnMap;
		}else{
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "");
			rtnMap.put("userVouchers", userVouchers);
			return rtnMap;
		}
	}
	
	/**
	 * 根据产品ID获取代金券
	 */
	@Override
	public Map<String,Object> queryVouchersByLoanId(
			Map<String, Object> paramsMap) throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		Scattered sc = loanDao.queryScatteredByLoanId(paramsMap);
		if(sc!=null){
			//产品ID
			String productType = sc.getPlanId().toString();
			paramsMap.put("productType", productType);
			if(productType.equals("108")){
				if(sc.getRemanDays()!=null && sc.getRemanDays()>0){
					paramsMap.put("remanPeriods", sc.getRemanDays());
				}else{
					paramsMap.put("remanPeriods", sc.getRemanPeriods()*30);
				}
			}
			
		}else{
			rtnMap.put("rescode", Consts.ERROR_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "代金券不存在！");
			return rtnMap;
		}
		
		List<UserVouchers> userVoucherList = userVouchersDao.queryVochersByUserId(paramsMap);
		
		int totalNum = userVouchersDao.queryVochersByUserIdCount(paramsMap);
		
		rtnMap.put("list", userVoucherList);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		rtnMap.put("listSize", userVoucherList.size());
		rtnMap.put("totalNum", totalNum);
		
		return rtnMap;
	}
	
	@Override
	public Map<String, Object> queryVochersInfoById(String voucher_type_id) {
		// TODO Auto-generated method stub
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		Map<String,Object> paramsMap = new HashMap<String,Object>();
		paramsMap.put("voucherId", voucher_type_id);
		VouchersRule vouchersRule = this.userVouchersDao.queryVouchersRuleById(paramsMap);
		
		if(vouchersRule==null){
			rtnMap.put("rescode", Consts.ERROR_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "库存不足代金券异常");
			return rtnMap;
		}else{
			rtnMap.put("rescode", Consts.SUCCESS_CODE);
			rtnMap.put("resmsg", "");
			rtnMap.put("resmsg_cn", "");
			rtnMap.put("vouchersRule", vouchersRule);
			return rtnMap;
		}
	}
	
	/**
	 * 获取活期代金券数量
	 */
	@Override
	public Map<String,Object> queryVouchersCount(
			Map<String, Object> paramsMap) throws Exception {
		Map<String,Object> rtnMap = new HashMap<String,Object>();
		
		int totalNum = userVouchersDao.queryVochersByUserIdCount(paramsMap);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		rtnMap.put("vouchersCount", totalNum);
		return rtnMap;
	}

	@Override
	public Map<String, Object> myVouchers2(Map<String, Object> paramsMap) throws Exception {

		Map<String,Object> rtnMap = new HashMap<String,Object>();
		String userId = paramsMap.get("userId").toString();
		String loanId = paramsMap.get("loanId")==null?"":paramsMap.get("loanId").toString();
		
		if(StringUtils.isNotBlank(loanId)){
			Scattered sc = loanDao.queryScatteredByLoanId(paramsMap);//查询标的信息
			if(sc!=null){
				//产品ID
				String productType = sc.getPlanId().toString();
				paramsMap.put("productType", productType);
				if(productType.equals("108")){
					if(sc.getRemanDays()!=null && sc.getRemanDays()>0){
						paramsMap.put("remanPeriods", sc.getRemanDays());
					}else{
						paramsMap.put("remanPeriods", sc.getRemanPeriods()*30);
					}
				}
			}
		}else if (null!=paramsMap.get("remanPeriods")&&!"".equals(paramsMap.get("remanPeriods"))) {
			paramsMap.put("remanPeriods", new BigDecimal(paramsMap.get("remanPeriods").toString()).multiply(new BigDecimal(30)));
		}
		
		List<UserVouchers> userVoucherList = userVouchersDao.queryVochersByUserId(paramsMap);
		int totalNum = userVouchersDao.queryVochersByUserIdCount(paramsMap);
		List<UserVouchersVo> list  = new ArrayList<UserVouchersVo>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
		for(UserVouchers uv :userVoucherList){
			UserVouchersVo vo = new UserVouchersVo();
			vo.setUserId(Long.parseLong(userId));
			vo.setVoucherAmount(uv.getVoucher_amount().toString());
			String voucherDesc = "投资满"+uv.getInvestment_amount().toString()+"元可用";
			vo.setVoucherDesc(voucherDesc);
			paramsMap.put("voucherId", uv.getVoucher_type_id());
			VouchersRule vouchersRule = this.userVouchersDao.queryVouchersRuleById(paramsMap);
			
			vo.setVouchersRule(vouchersRule);
			String validityPeriodDesc = sdf.format(uv.getEnddate())+"到期";
			vo.setValidityPeriodDesc(validityPeriodDesc);
			vo.setVoucherId(uv.getId().toString());
			vo.setVoucherTypeId(vouchersRule.getProduct_type());
			vo.setInvestmentAmount(uv.getInvestment_amount().toString());
			//拉取适合此代金券的产品
			/*String scatteredLoanDesc = "";*/
			if(vouchersRule.getProduct_type().equals("108")){
				paramsMap.put("voucherProductType", vouchersRule.getProduct_type());
				paramsMap.put("voucherMinlockperiod", vouchersRule.getMinlockperiod());
				List<Scattered> scatteredList = this.loanDao.queryScatteredByVouchersId(paramsMap);
				for(Scattered st:scatteredList){
					//finishedRatio去掉小数点，取整数
					BigDecimal finishedRatio =st.getFinishedRatio();
					BigDecimal bigFinishedRatio = DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(finishedRatio)>0&& BigDecimal.ZERO.compareTo(finishedRatio)<0?BigDecimal.ONE:finishedRatio);
					st.setFinishedRatio(bigFinishedRatio);
				}
				vo.setScatteredList(scatteredList);
				/*for(Scattered st:scatteredList){
					scatteredLoanDesc += st.getProductName()+"、";
				}*/
			}else if(vouchersRule.getProduct_type().equals("109")){
				paramsMap.put("finaceId", "1");
				paramsMap.put("startSellingTime",CommonUtil.getDateYYYYMMDDHH24MM());
				List<Scattered_sssq> scatteredListSssq = this.depositDao.queryScatteredLoanInfo(paramsMap);
				List<Scattered> scatteredList  = new ArrayList<Scattered>();
				for(Scattered_sssq st:scatteredListSssq){
					//finishedRatio去掉小数点，取整数
					BigDecimal finishedRatio =st.getFinishedRatio();
					BigDecimal bigFinishedRatio = DecimalFormatUtil.getDecimalFormat0(BigDecimal.ONE.compareTo(finishedRatio)>0&& BigDecimal.ZERO.compareTo(finishedRatio)<0?BigDecimal.ONE:finishedRatio);
					st.setFinishedRatio(bigFinishedRatio);
					/*scatteredLoanDesc += st.getProductName()+"、";*/
					if(st.getFinishedRatio().compareTo(new BigDecimal(100))<0){
						Scattered scattered = st;
						scatteredList.add(scattered);
					}
					
				}
				vo.setScatteredList(scatteredList);
			}
			/*if(StringUtils.isNotBlank(scatteredLoanDesc)){
				scatteredLoanDesc = scatteredLoanDesc.substring(0,scatteredLoanDesc.length()-2);
			}*/
			
			vo.setScatteredLoanDesc(vouchersRule.getProduct_type_desc());
			list.add(vo);
		}
		rtnMap.put("list", list);
		rtnMap.put("rescode", Consts.SUCCESS_CODE);
		rtnMap.put("resmsg_cn", "查询成功"); 
		rtnMap.put("listSize", userVoucherList.size());
		rtnMap.put("totalNum", totalNum);
		
		/** 将数据同步到Redis **/
		/*RedisOperateUtil.rpushObjectAll(RedisContant.KEY_VOUCHERS_LIST +  userId, list);
		RedisOperateUtil.setString(RedisContant.KEY_VOUCHERS_LIST_TOTAL_NUM + userId, String.valueOf(totalNum));
		*/
		return rtnMap;
	}
}
